<?php

class FavoritesController extends AppController {

	var $name = 'Favorites';
	public $layout = 'user_default';
	var $components = array(
			'Auth' => array(
					'authenticate' => array(
							'Form'=>array(
									'userModel' => 'User','recursive' => 1,
									'fields'=>array(
											'username'=>'email',
											'password'=>'password'
									)
							),
					),
			),
			'ScoreHook',
	);
	
	public function edit($id) {
	    $item = $this->Favorite->find('first',array(
	        'conditions'=> array('id' => $id,'creator_id'=>$this->currentUser['id']),
	        'recursive' => -1,
	        'fields' => array('id','name','cate_id','model','data_id','creator_id'),
	    ));
	    if( !empty($item) ) {
	        
	        if($this->data) {
	            $this->data['creator_id'] = $this->currentUser['id'];
	            if( $this->Favorite->save($this->data) ){
	                $resultinfo = array(
	                    'ret' => 0,
	                    'msg'=> '保存成功',
	                    'tasks' => array(array('dotype'=>'close_dialog')) ,
	                );
	                echo json_encode($resultinfo);
	            }
	            else{
	                $resultinfo = array(
	                    'ret' => -1,
	                    'msg'=> '保存失败',
	                );
	                echo json_encode($resultinfo);
	            }
	            exit;
	        }
	        else{
	            
	            $this->loadModel('UserCate');
	            $cates = $this->UserCate->getCateList('Favorite',$this->currentUser['id'],'',true);
	            $this->set('cates',$cates);
	            
	            $data_model = $item['Favorite']['model'];
	            $data_id = $item['Favorite']['data_id'];
	            $this->loadModel($data_model);
	           
	            $this->set('data_info',$item[$data_model]);
	            $this->set('data_model',$data_model);
	            $this->set('data_id',$data_id);
	            $this->data = $item;
	        }
	    }
	    else{
	        $this->__message('参数错误');
	    }
	    
	    $this->set('id',$id);
	}
	
	function add()
	{
		$this->autoRender = false;

		$modelClass = $this->modelClass;
		
		if(empty($this->currentUser) || empty($this->currentUser['id'])){
			$errorinfo = array(
				'ret' => -1,
				'msg'=> __('Your need to login'),
				'tasks'=>array(
					array(
						'dotype'=> 'callback',
						'callback'=> 'publishController.open_dialog',//'showErrorMessage',//publishController.open_dialog',
						'thisArg'=> 'publishController',
						'callback_args' => array('url'=>Router::url('/users/login'),'options'=>array('title'=> __('Your need to login'))),
					)
				)
			);
			echo json_encode($errorinfo);
			return false;
		}
		else if($this->data[$modelClass]['model'] == 'Color' && count($this->currentUser['role_id']) < 2 ) {
		    $errorinfo = array(
		        'ret' => -1,
		        'msg'=> '付费后才可收藏配色方案',
		    );
		    echo json_encode($errorinfo);
		    return false;
		}
		
		
		$this->data[$modelClass]['published'] = 1;
		$this->data[$modelClass]['deleted'] = 0;
		$this->data[$modelClass]['click_nums'] = 0;
		
		
		
		$this->data[$modelClass]['created'] = $this->data[$modelClass]['updated'] = date('Y-m-d H:i:s');
		
		$data_model = $this->data[$modelClass]['model'];
		$data_id = $this->data[$modelClass]['data_id'];
		
		$hasfavored = $this->{$modelClass}->find('first',array('conditions'=>array(
			'model'=> $data_model,
			'data_id'=> $data_id,
			'creator_id' => $this->currentUser['id'],				
		)));
		if(!empty($hasfavored)){
			$errorinfo = array('ret' =>0,'msg'=> __('Favorite '.$data_model.' Successfully'));
			echo json_encode($errorinfo);
			return false;
		}
		// 查看对应的数据是否存在
		$this->loadModel($data_model);
		$this->{$data_model}->recursive = -1;
		
		$fields = array('id','created');
		
		$schema = $this->{$data_model}->schema();
		if( isset($schema['score']) ) {
			$fields[] = 'score';
		}
		if( isset($schema['price']) ) {
			$fields[] = 'price';
		}
		if($data_model == 'EditorStyle') {
			if( isset($schema['wechat_auth']) ) {
				$fields[] = 'wechat_auth';
				$fields[] = 'only_paid';
			}
		}
		
		$data = $this->{$data_model}->find('first',array(
			'conditions' => array( 'id' => $data_id ),
			'fields'=> $fields,
			'recursive' => -1,
		));
		if(empty($data)){
			$errorinfo = array('ret' =>-1,'msg'=> __('Data not exists.'));
			echo json_encode($errorinfo);
			return false;
		}
		
		if($data_model == 'EditorStyle') {

			if( $data[$data_model]['wechat_auth'] > 0 && count($this->currentUser['role_id'])== 1 ) {
				$user_wxes = $this->Session->read('User.wxes');
				if( empty($user_wxes) ) {
				    $errorinfo = array('ret' =>-17,'msg'=> '此样式必须升级VIP或者授权微信公众号才可收藏使用');
					echo json_encode($errorinfo);
					return false;
				}
			}
			if( $data[$data_model]['only_paid'] > 0 && count($this->currentUser['role_id'])== 1 ) {
					$errorinfo = array('ret' =>-1,'msg'=> '此样式限VIP会员使用');
					echo json_encode($errorinfo);
					return false;
			}
		    if( $data[$data_model]['price'] > 0 ) {
		        // 付费样式，禁止收藏
		        $errorinfo = array('ret' =>-1,'msg'=> __('Charge template do not support favorite.'));
		        echo json_encode($errorinfo);
		        return false;
		    }
		    else if( count($this->currentUser['role_id']) < 2 ) { // 非付费会员，收藏总数限制, 5天滞后期
		        $created = strtotime( $data[$data_model]['created'] );
		        $validate = time() - 86400 * 5; // 7天前的日期
		        if( $created > $validate ) {
		            $errorinfo = array('ret' =>-1,'msg'=> '免费会员在新样式上线5天后，才能收藏使用。升级付费会员无限制。');
		            echo json_encode($errorinfo);
		            return false;
		        }
		        
		        $total_nums = $this->Favorite->find('count',array('conditions'=>array(
		            'model'=> $data_model,
		            'cate_id <>' => 3,
		            'creator_id' => $this->currentUser['id'],
		        )));
		        if( $total_nums >= 800 ) {
		            $errorinfo = array('ret' =>-1,'msg'=> '共收藏‘'.$total_nums.'’条,免费用户最多允许收藏800个样式.<br/>升级VIP，收藏数目无限制。');
		            echo json_encode($errorinfo);
		            return false;
		        }
		    }

// 		    else {
// 		        // 付费会员。
// 		        if( count($this->currentUser['role_id'])== 2 && in_array(8,$this->currentUser['role_id']) ){ //初级付费会员，3天滞后期
// 		            $created = strtotime( $data[$data_model]['created'] );
// 		            $validate = time() - 86400 * 3; // 3天前的日期
// 		            if( $created > $validate ) {
// 		                $errorinfo = array('ret' =>-1,'msg'=> '初级会员新样式添加3天后，才能收藏使用。升级中高级会员可去除限制。');
// 		                echo json_encode($errorinfo);
// 		                return false;
// 		            }
// 		        }
// 		    }
		}
		
		if( $data[$data_model]['score'] && count($this->currentUser['role_id'])==1 && ! $this->ScoreHook->checkscore($this,$data_model,'addfavor',$data[$data_model]['score']) ){
			$errorinfo = array('ret' =>-1,'msg'=> __('Your score is not enought'));
			echo json_encode($errorinfo);
			return false;
		}
		
		$this->{$modelClass}->create();
		$this->data[$modelClass]['creator_id'] = $this->currentUser['id'];
		unset( $this->data[$modelClass]['id'] );
		
		if ($this->{$modelClass}->save($this->data)) {
			
			$schema = $this->{$data_model}->schema();
			if(isset($schema['favor_nums'])) { //有收藏次数的字段
				$this->{$this->data[$modelClass]['model']}->updateAll(array('favor_nums'=>'favor_nums+1'),array('id'=>$data_id));
			}
			
			$successinfo = array('ret' =>0,'msg'=> __('Favorite '.$data_model.' Successfully'),
				'data'=>array(
					'model'=> $this->data[$modelClass]['model'],
					'data_id'=> $this->data[$modelClass]['data_id']
			));	
			
			if($data_model == 'EditorStyle') {
			    Cache::delete('favor_styles_'.$this->currentUser['id']);
			}
			// 考虑是否付费会员不扣积分，仅免费会员扣积分 
			if( $data[$data_model]['score']  && count($this->currentUser['role_id'])== 1 ) {
    			$hook_results = $this->Hook->call('favorSuccess',array($data_id,$data_model,-$data[$data_model]['score']));
    			$action_score = $hook_results['ScoreHook']; unset($hook_results['ScoreHook']);
				if($action_score > 0){
					$successinfo['msg'] .= '<BR><BR><div class="alert alert-warning alert-score text-center">'.__('Increase Score').' +'.$action_score.'</div>';
				}
				elseif($action_score < 0){
					$successinfo['msg'] .= '<BR><BR><div class="alert alert-warning alert-score text-center">'.__('Decrease Score').' '.$action_score.'</div>';
				}
			}
			
			echo json_encode($successinfo);
        	return ;
		}else {
			// 保存发生错误，删除对应的收藏
			echo json_encode($this->{$this->modelClass}->validationErrors);
	        return ;
		}
	}
	
	public function refresh($id){
		if(empty($this->currentUser['id'])){
			echo json_encode(array('error'=>__('Need login'),'ret'=> -1));
		}
		elseif(empty($id)){
			echo json_encode(array('error'=> __('Params error'),'ret'=> -1));
		}
		else{
			$item = $this->{$this->modelClass}->find('first',array(
					'conditions'=> array('id' => $id,'creator_id'=>$this->currentUser['id']),
					'recursive' => -1,
					'fields' => array('id','model','data_id','creator_id'),
			));
			
			if($item[$this->modelClass]['model'] == 'EditorStyle') {
			    Cache::delete('favor_styles_'.$this->currentUser['id']);
			}
			
			if( empty($item) ){
				echo json_encode(array('error'=> __('Forbit operate.'),'ret'=> -1));
			}
			else{
				$this->{$this->modelClass}->updateAll(array('updated'=>'CURRENT_TIMESTAMP'),array($this->modelClass.'.id' => $id,'creator_id'=>$this->currentUser['id']));
				echo json_encode(array('ret'=> 0,'msg'=>__('Moved first successfully')));
			}
		}
		exit;
	}

	function cancelByMid($model,$data_id){
        $item = $this->{$this->modelClass}->find('first',array(
            'conditions'=> array('model'=>$model,'data_id' => $data_id,'creator_id'=>$this->currentUser['id']),
            'recursive' => -1,
            'fields' => array('id','model','data_id','creator_id'),
        ));

        if( empty($item)){
            echo json_encode(array('msg'=>  __('Unfavorite Successfully'),'ret'=> 0));
        }
        else{
            $this->loadModel($item['Favorite']['model']);
            $schema = $this->{$item['Favorite']['model']}->schema();
            if(isset($schema['favor_nums'])){
                $this->{$item['Favorite']['model']}->updateAll(array('favor_nums'=>'favor_nums-1'),array('id'=>$item['Favorite']['data_id']));
            }
            $this->{$this->modelClass}->deleteAll(array('Favorite.id' => $item['Favorite']['id']), true, true);
            echo json_encode(array('ret' =>0,'msg'=> __('Unfavorite Successfully')));
        }
    }
	
	
	public function cancel($id){
		if(empty($this->currentUser['id'])){
			echo json_encode(array('msg'=>__('Need login'),'ret'=> -1));
		}
		elseif(empty($id)){
			echo json_encode(array('msg'=> __('Params error'),'ret'=> -1));
		}
		else{
			$item = $this->Favorite->find('first',array(
				'conditions'=> array('id' => $id,'creator_id'=>$this->currentUser['id']),
				'recursive' => -1,
				'fields' => array('id','model','data_id','creator_id'),
			));
			if( empty($item)){
			    echo json_encode(array('msg'=> '没有收藏，可能已经取消过收藏了','ret'=> -1));
			}
			else{
				$this->loadModel($item['Favorite']['model']);
				$schema = $this->{$item['Favorite']['model']}->schema();
				if(isset($schema['favor_nums'])){
					$this->{$item['Favorite']['model']}->updateAll(array('favor_nums'=>'favor_nums-1'),array('id'=>$item['Favorite']['data_id']));
				}
				$this->{$this->modelClass}->deleteAll(array('Favorite.id' => $id,'creator_id'=>$this->currentUser['id']), true, true);
				echo json_encode(array('ret' =>0,'msg'=> __('Unfavorite Successfully')));
			}
		}
		exit;
	}
	
	public function mine($model='Task'){
	
		$this->pageTitle = __('Watch list');
	
		$pagesize = intval(Configure::read('Favorite.pagesize'));
		if(!$pagesize){
			$pagesize = 15;
		}
		$page = $_REQUEST['page'] ? $_REQUEST['page']:1;
		
		$this->loadModel($model);
		
		$schema = $this->{$model}->schema();
		$fields = array_keys($schema);
		
		$conditions = array('Favorite.creator_id' => $this->currentUser['id'],'Favorite.model'=>$model);
		
		if(!empty($_REQUEST['cate_id'])) {
		    $conditions[$model.'.cate_id'] = $_REQUEST['cate_id'];
		}
		
		foreach($fields as $f){
		    if(isset($_REQUEST[$f])) {
		        $conditions[$model.'.'.$f] = $_REQUEST[$f];
		    }
		}
		
		if($model == 'Image' && $_REQUEST['type'] == 'image') {
		    $conditions[$model.'.cate_id not'] = array(84,85);
		}
	
		$total = $this->Favorite->find('count', array(
				'conditions' => $conditions,
				'recursive' => -1,
				'joins' => array(
					array('table'=> Inflector::tableize($model),'alias'=> $model,'type'=>'inner','conditions'=> array('Favorite.data_id = '.$model.'.id'))
				),
		));
		
		$table_prefix = $this->currentUser['id'] % 256 ;
		
		
		
	
		
		$datalist = $this->{$model}->find('all', array(
				'conditions' => $conditions,
				'joins' => array(
						array('table'=>'favorites_'.$table_prefix,'alias'=>'Favorite','type'=>'inner','conditions'=> array('Favorite.data_id = '.$model.'.id'))
				),
				'order'=>'Favorite.updated desc',
				'recursive' => 1,
				'limit' => $pagesize,
				'page' => $page,
				'fields' => array('*'),
		));
		
		/**设置 $fovarited_list，使列表中使用与_list相同的模板 **/
		$fovarited_list = array();
		foreach($datalist as $item) {
		    if(isset($item['Favorite']['id'])) {
		      $fovarited_list[$item['Favorite']['id']] = $item[$model]['id'];
		    }
		}
		$this->set('fovarited_list',$fovarited_list);
	
		$page_navi = getPageLinks($total, $pagesize, '/favorites/mine/'.$model, $page);
		$this->set('datalist',$datalist);
		$this->set('model',$model);
		$this->set('page_navi', $page_navi);
	
	}
	
}
?>